package com.likai.monitor.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.likai.monitor.mapper.MServersMapper;
import com.likai.monitor.vo.MServers;
import com.likai.monitor.vo.SystemInfo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/check")
@RestController
public class CheckController {
    @Autowired
    MServersMapper mServersMapper;


    @RequestMapping("/getAllInfo")
    public String getAllInfo() throws Exception {
//
//        List<String> ips=new ArrayList<>();
//
//        ips.add("192.168.0.111");
//        ips.add("192.168.0.98");

        List<MServers> ipst=new ArrayList<>();
        ipst=mServersMapper.selectList(null);
        System.out.println(ipst.size());
        List<SystemInfo> list=new ArrayList<>();

        for (MServers mServers : ipst){
            try {


                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url("http://" + mServers.getIp() + ":65530/monitor/getSystemInfo")
                        .method("GET", null)
                        .build();
                Response response = client.newCall(request).execute();
                SystemInfo s = JSONObject.parseObject(response.body().string(), SystemInfo.class);
                s.setName(mServers.getName());
                s.setDepart(mServers.getDepart());
                s.setPerson(mServers.getPerson());
                s.setIp(mServers.getIp());
                list.add(s);
            }catch (Exception e ) {
                SystemInfo s = new SystemInfo();
                s.setIp(mServers.getIp());
                s.setName(mServers.getName());
                s.setDepart(mServers.getDepart());
                s.setPerson(mServers.getPerson());
                s.setSysInfo("无法连接,请检查");
                list.add(s);
            }
        }

        return JSONArray.toJSONString(list);
    }
}
